# game_engine/game_state.py
from enum import Enum
from dataclasses import dataclass
from typing import Dict, List, Tuple, Optional
import numpy as np
import json
from datetime import datetime

class FactorType(Enum):
    """十二因子类型枚举"""
    MYDEI = "万敌"        # 烧血反击特化 [火种：纷争]
    HYACINE = "风堇"      # 治疗辅助特化 [火种：天空]  
    TRIBBIE = "缇宝"      # 空间移动特化 [火种：门径]
    AGLAEA = "阿格莱雅"   # 高速召唤特化 [火种：浪漫]
    ANAXA = "那刻夏"      # 多段攻击特化 [火种：理性]  
    CASTORICE = "遐蝶"    # 烧血爆发特化 [火种：死亡]
    CIPHER = "赛飞儿"     # 高速追击特化 [火种：诡计]
    HYSILENS = "海瑟音"   # 持续伤害特化 [火种：海洋]  
    CERYDRA = "刻律德菈"  # 战技辅助特化 [火种：律法]
    TERRAE = "丹恒腾荒"   # 护盾召唤特化 [火种：大地]
    EVERNIGHT = "长夜月"  # 召唤辅助特化 [火种：忘却]  
    PHAINON = "白厄"      # 变身跑条特化 [火种：负世]

@dataclass
class FactorAttributes:
    """因子属性配置"""
    base_attack: float = 10.0
    base_defense: float = 10.0
    base_health: float = 100.0
    base_healing: float = 10.0
    base_mobility: float = 10.0
    base_perception: float = 10.0
    special_ability: str = ""
    growth_rates: Dict[str, float] = None
    
    def __post_init__(self):
        if self.growth_rates is None:
            self.growth_rates = {
                'attack': 1.0, 'defense': 1.0, 'health': 1.0,
                'healing': 1.0, 'mobility': 1.0, 'perception': 1.0
            }

class FactorDevelopment:
    """因子发展状态"""
    def __init__(self, factor_type: FactorType, name: str, spark_type: str):
        self.factor_type = factor_type
        self.name = name
        self.spark_type = spark_type  # 火种类型
        self.level = 1
        self.experience = 0.0
        self.attributes = self._get_base_attributes()
        self.skills = self._get_initial_skills()
        self.current_location = (0.0, 0.0)
        self.destination = None
        self.travel_progress = 0.0
        self.travel_speed = 1.0
        self.development_path = []
        self.is_alive = True
        self.special_charges = 3  # 特殊能力使用次数
        self.buffs = []
        self.debuffs = []
        
    def _get_base_attributes(self) -> Dict[str, float]:
        """根据因子类型获取基础属性"""
        base_configs = {
            FactorType.MYDEI: FactorAttributes(
                base_attack=25, base_health=120, base_defense=15,
                special_ability="burn_blood_counter",
                growth_rates={'attack': 2.0, 'health': 1.5, 'defense': 1.3}
            ),
            FactorType.HYACINE: FactorAttributes(
                base_healing=30, base_health=110, base_defense=12,
                special_ability="sky_healing", 
                growth_rates={'healing': 2.5, 'health': 1.2, 'defense': 1.1}
            ),
            FactorType.TRIBBIE: FactorAttributes(
                base_mobility=35, base_perception=20,
                special_ability="pathway_teleport",
                growth_rates={'mobility': 3.0, 'perception': 2.0, 'attack': 0.8}
            ),
            FactorType.AGLAEA: FactorAttributes(
                base_attack=18, base_mobility=25,
                special_ability="romantic_summon",
                growth_rates={'attack': 1.8, 'mobility': 2.2, 'healing': 1.2}
            ),
            FactorType.ANAXA: FactorAttributes(
                base_attack=22, base_mobility=18,
                special_ability="rational_multi_attack",
                growth_rates={'attack': 2.2, 'mobility': 1.5, 'defense': 1.0}
            ),
            FactorType.CASTORICE: FactorAttributes(
                base_attack=28, base_health=90, base_defense=8,
                special_ability="death_blossom",
                growth_rates={'attack': 2.8, 'health': 0.9, 'defense': 0.7}
            ),
            FactorType.CIPHER: FactorAttributes(
                base_attack=20, base_mobility=30, base_perception=25,
                special_ability="trick_pursuit",
                growth_rates={'attack': 1.9, 'mobility': 2.8, 'perception': 2.2}
            ),
            FactorType.HYSILENS: FactorAttributes(
                base_attack=16, base_health=130, base_defense=14,
                special_ability="ocean_song",
                growth_rates={'attack': 1.5, 'health': 1.8, 'defense': 1.4}
            ),
            FactorType.CERYDRA: FactorAttributes(
                base_defense=20, base_healing=15, base_health=115,
                special_ability="law_enhancement",
                growth_rates={'defense': 1.7, 'healing': 1.6, 'health': 1.3}
            ),
            FactorType.TERRAE: FactorAttributes(
                base_defense=25, base_health=140, base_attack=12,
                special_ability="earth_shield",
                growth_rates={'defense': 2.2, 'health': 1.9, 'attack': 0.9}
            ),
            FactorType.EVERNIGHT: FactorAttributes(
                base_healing=25, base_perception=18, base_health=105,
                special_ability="forget_summon",
                growth_rates={'healing': 2.0, 'perception': 1.8, 'health': 1.4}
            ),
            FactorType.PHAINON: FactorAttributes(
                base_mobility=40, base_attack=15, base_health=95,
                special_ability="negative_world_transform",
                growth_rates={'mobility': 3.2, 'attack': 1.4, 'health': 1.1}
            )
        }
        
        config = base_configs.get(self.factor_type, FactorAttributes())
        return {
            'attack': config.base_attack,
            'defense': config.base_defense,
            'health': config.base_health,
            'healing': config.base_healing,
            'mobility': config.base_mobility,
            'perception': config.base_perception
        }
    
    def _get_initial_skills(self) -> List[str]:
        """获取初始技能"""
        skill_map = {
            FactorType.MYDEI: ["血怒反击", "燃烧意志", "终末冲击"],
            FactorType.HYACINE: ["天愈术", "风之守护", "生命礼赞"],
            FactorType.TRIBBIE: ["空间跳跃", "门径穿梭", "维度折叠"],
            FactorType.AGLAEA: ["浪漫召唤", "速攻指令", "爱心爆弹"],
            FactorType.ANAXA: ["理性分析", "多段连击", "精确打击"],
            FactorType.CASTORICE: ["死亡绽放", "血蝶之舞", "终末华尔兹"],
            FactorType.CIPHER: ["诡计突袭", "速度爆发", "暗影追击"],
            FactorType.HYSILENS: ["海洋之歌", "潮汐波动", "深海压力"],
            FactorType.CERYDRA: ["律法审判", "战技强化", "秩序领域"],
            FactorType.TERRAE: ["大地守护", "护盾召唤", "岩壁防御"],
            FactorType.EVERNIGHT: ["忘却之月", "召唤增幅", "暗夜庇护"],
            FactorType.PHAINON: ["负世变身", "跑条加速", "形态切换"]
        }
        return skill_map.get(self.factor_type, ["基础攻击", "基础防御"])
    
    def use_special_ability(self) -> bool:
        """使用特殊能力"""
        if self.special_charges > 0:
            self.special_charges -= 1
            return True
        return False
    
    def level_up(self):
        """升级因子"""
        self.level += 1
        growth_config = self._get_base_attributes().growth_rates
        
        for attr, value in self.attributes.items():
            if attr in growth_config:
                self.attributes[attr] += growth_config[attr] * 5
        
        # 学习新技能
        if self.level in [5, 10, 15, 20]:
            new_skill = f"{self.factor_type.value}专属技能Lv{self.level}"
            if new_skill not in self.skills:
                self.skills.append(new_skill)
        
        self.experience = 0
        return f"{self.name} 升级到 {self.level} 级! 学会了新技能!"
    
    def move_to(self, destination: Tuple[float, float]):
        """移动到目标位置"""
        self.destination = destination
        self.travel_progress = 0.0
    
    def update_travel(self, delta_time: float):
        """更新移动进度"""
        if self.destination and self.travel_progress < 1.0:
            self.travel_progress += delta_time * self.attributes['mobility'] * 0.01
            if self.travel_progress >= 1.0:
                self.current_location = self.destination
                self.destination = None
                self.travel_progress = 0.0
                return True  # 到达目的地
        return False

class WorldEvent:
    """世界事件定义"""
    def __init__(self, name: str, trigger_time: int, location: Tuple[float, float], 
                 duration: int, rewards: Dict, requirements: Dict, description: str = ""):
        self.name = name
        self.trigger_time = trigger_time
        self.location = location
        self.duration = duration
        self.rewards = rewards
        self.requirements = requirements
        self.description = description
        self.participants = []
        self.active = False
        self.start_time = None
        self.completed = False
    
    def activate(self, current_time: int):
        """激活事件"""
        if not self.active and current_time >= self.trigger_time:
            self.active = True
            self.start_time = current_time
            return True
        return False
    
    def update(self, current_time: int):
        """更新事件状态"""
        if self.active and not self.completed:
            if current_time >= self.start_time + self.duration:
                self.complete()
                return True
        return False
    
    def complete(self):
        """完成事件"""
        self.active = False
        self.completed = True
        return self.rewards

class GameWorld:
    """游戏世界状态管理"""
    def __init__(self):
        self.factors = []
        self.lygus = LygusState()  # 修改为Lygus
        self.iron_curtain_progress = 0
        self.current_cycle = 0
        self.current_time = 0
        self.total_time = 1000
        self.events = []
        self.titan_events = self._init_titan_events()
        self.game_log = []
        
    def _init_titan_events(self) -> Dict:
        """初始化12泰坦事件，对应12火种"""
        return {
            # 纷争泰坦 - 对应万敌
            "strife_titan": WorldEvent(
                name="纷争泰坦觉醒",
                trigger_time=100,
                location=(15, 15),
                duration=45,
                rewards={"attack": 50, "special_ability_boost": "blood_rage"},
                requirements={"min_level": 5, "factor_type": FactorType.MYDEI},
                description="纷争泰坦从战火中诞生，只有真正的战士才能直面它的怒火"
            ),
            # 天空泰坦 - 对应风堇
            "sky_titan": WorldEvent(
                name="天空泰坦讨伐",
                trigger_time=200,
                location=(50, 50),
                duration=50,
                rewards={"health": 100, "healing": 50, "special_buff": "titan_slayer"},
                requirements={"min_level": 8, "factor_type": FactorType.HYACINE},
                description="传说中的天空泰坦出现在云端，击败它可获得强大的治愈力量"
            ),
            # 门径泰坦 - 对应缇宝
            "gateway_titan": WorldEvent(
                name="门径泰坦显现",
                trigger_time=150,
                location=(70, 30),
                duration=40,
                rewards={"mobility": 60, "perception": 40, "special_ability": "dimension_walk"},
                requirements={"min_level": 7, "factor_type": FactorType.TRIBBIE},
                description="门径泰坦掌控空间法则，穿越维度挑战它的权威"
            ),
            # 浪漫泰坦 - 对应阿格莱雅
            "romance_titan": WorldEvent(
                name="浪漫泰坦之歌",
                trigger_time=250,
                location=(35, 65),
                duration=55,
                rewards={"healing": 45, "mobility": 35, "summon_boost": 2.0},
                requirements={"min_level": 9, "factor_type": FactorType.AGLAEA},
                description="浪漫泰坦用爱与美的力量守护着这片土地"
            ),
            # 理性泰坦 - 对应那刻夏
            "reason_titan": WorldEvent(
                name="理性泰坦试炼",
                trigger_time=180,
                location=(60, 40),
                duration=48,
                rewards={"attack": 55, "perception": 30, "multi_attack_bonus": 1.5},
                requirements={"min_level": 8, "factor_type": FactorType.ANAXA},
                description="理性泰坦考验着挑战者的智慧与计算能力"
            ),
            # 死亡泰坦 - 对应遐蝶
            "death_titan": WorldEvent(
                name="死亡泰坦降临",
                trigger_time=300,
                location=(20, 20),
                duration=70,
                rewards={"attack": 90, "special_charges": 2, "death_aura": True},
                requirements={"min_level": 12, "factor_type": FactorType.CASTORICE},
                description="死亡泰坦带来毁灭与重生，只有强者才能直面死亡"
            ),
            # 诡计泰坦 - 对应赛飞儿
            "trickery_titan": WorldEvent(
                name="诡计泰坦谜题",
                trigger_time=220,
                location=(45, 55),
                duration=42,
                rewards={"mobility": 70, "perception": 50, "pursuit_damage": 1.8},
                requirements={"min_level": 10, "factor_type": FactorType.CIPHER},
                description="诡计泰坦设下重重陷阱，只有最敏捷的因子才能破解"
            ),
            # 海洋泰坦 - 对应海瑟音
            "ocean_titan": WorldEvent(
                name="海洋泰坦入侵",
                trigger_time=280,
                location=(80, 20),
                duration=55,
                rewards={"healing": 70, "health": 80, "special_buff": "ocean_blessing"},
                requirements={"min_level": 11, "factor_type": FactorType.HYSILENS},
                description="海洋泰坦从深海崛起，带来滔天巨浪和持续伤害"
            ),
            # 律法泰坦 - 对应刻律德菈
            "law_titan": WorldEvent(
                name="律法泰坦审判",
                trigger_time=320,
                location=(25, 75),
                duration=65,
                rewards={"defense": 85, "healing": 40, "skill_enhancement": True},
                requirements={"min_level": 13, "factor_type": FactorType.CERYDRA},
                description="律法泰坦维护着世界的秩序，挑战它需要绝对的纪律"
            ),
            # 大地泰坦 - 对应丹恒腾荒
            "earth_titan": WorldEvent(
                name="大地泰坦觉醒", 
                trigger_time=260,
                location=(30, 70),
                duration=60,
                rewards={"defense": 80, "health": 120, "shield_strength": 2.0},
                requirements={"min_level": 11, "factor_type": FactorType.TERRAE},
                description="沉睡的大地泰坦苏醒，它的力量足以改变战局"
            ),
            # 忘却泰坦 - 对应长夜月
            "forgetfulness_titan": WorldEvent(
                name="忘却泰坦梦境",
                trigger_time=240,
                location=(55, 45),
                duration=52,
                rewards={"perception": 65, "healing": 55, "summon_duration": 1.7},
                requirements={"min_level": 10, "factor_type": FactorType.EVERNIGHT},
                description="忘却泰坦隐藏在记忆的迷雾中，只有洞察真相者才能找到它"
            ),
            # 负世泰坦 - 对应白厄
            "negative_world_titan": WorldEvent(
                name="负世泰坦侵蚀",
                trigger_time=350,
                location=(10, 10),
                duration=75,
                rewards={"mobility": 90, "transform_boost": 2.5, "special_ability": "world_walker"},
                requirements={"min_level": 15, "factor_type": FactorType.PHAINON},
                description="负世泰坦试图吞噬现实，只有能够驾驭形态变化的因子才能阻止它"
            )
        }
    
    def add_factor(self, factor: FactorDevelopment):
        """添加因子到世界"""
        self.factors.append(factor)
        self._log_event(f"{factor.name} 加入了翁法罗斯世界")
    
    def update_world(self, delta_time: float):
        """更新世界状态"""
        self.current_time += delta_time
        
        # 更新因子移动
        for factor in self.factors:
            if factor.update_travel(delta_time):
                self._log_event(f"{factor.name} 到达了目的地")
        
        # 检查并激活事件
        for event in self.events + list(self.titan_events.values()):
            if event.activate(int(self.current_time)):
                self._log_event(f"事件触发: {event.name}")
        
        # 更新活跃事件
        for event in self.events + list(self.titan_events.values()):
            if event.update(int(self.current_time)):
                rewards = event.complete()
                self._log_event(f"事件完成: {event.name}, 奖励: {rewards}")
        
        # 检查铁幕进度
        if self.current_time >= self.total_time:
            self.iron_curtain_progress += 10
            self._log_event(f"铁幕进度增加! 当前: {self.iron_curtain_progress}%")
    
    def _log_event(self, message: str):
        """记录游戏事件"""
        log_entry = {
            "timestamp": self.current_time,
            "message": message,
            "cycle": self.current_cycle
        }
        self.game_log.append(log_entry)
        print(f"[Cycle {self.current_cycle}] {message}")

class LygusState:
    """Lygus状态"""
    def __init__(self):
        self.health = 10000
        self.attack = 500
        self.defense = 300
        self.level = 50
        self.skills = ["暗影冲击", "灵魂撕裂", "末日预言"]
        self.is_awakened = False
        
    def take_damage(self, damage: float):
        """承受伤害"""
        actual_damage = max(0, damage - self.defense * 0.1)
        self.health -= actual_damage
        return actual_damage
    
    def awaken(self):
        """觉醒形态"""
        if not self.is_awakened and self.health <= 3000:
            self.is_awakened = True
            self.attack *= 1.5
            self.defense *= 1.3
            return True
        return False

class IronTombState:
    """铁墓状态"""
    def __init__(self):
        self.is_active = False
        self.progress = 0
        self.unlocked_factors = []
        self.required_factors = 6  # 需要至少6个因子才能激活铁墓
        self.completion_rewards = {
            "eternal_spark": 1,
            "legendary_equipment": 3,
            "special_evolution": True
        }
    
    def activate(self, factors_count: int) -> bool:
        """激活铁墓"""
        if factors_count >= self.required_factors and not self.is_active:
            self.is_active = True
            self.progress = 0
            return True
        return False
    
    def update_progress(self, delta_progress: float):
        """更新铁墓进度"""
        if self.is_active:
            self.progress += delta_progress
            if self.progress >= 100:
                self.complete()
    
    def complete(self):
        """完成铁墓挑战"""
        self.is_active = False
        return self.completion_rewards
    
    def add_unlocked_factor(self, factor_type: FactorType):
        """添加已解锁的因子"""
        if factor_type not in self.unlocked_factors:
            self.unlocked_factors.append(factor_type)
    
    def can_activate(self, factors_count: int) -> bool:
        """检查是否可以激活铁墓"""
        return factors_count >= self.required_factors and len(self.unlocked_factors) >= 3

# 在GameWorld类中添加铁墓状态
GameWorld.iron_tomb = IronTombState()

def save_game_state(world: GameWorld, filename: str):
    """保存游戏状态到文件"""
    save_data = {
        "current_time": world.current_time,
        "current_cycle": world.current_cycle,
        "iron_curtain_progress": world.iron_curtain_progress,
        "factors": [
            {
                "type": factor.factor_type.value,
                "name": factor.name,
                "level": factor.level,
                "location": factor.current_location,
                "attributes": factor.attributes,
                "skills": factor.skills
            }
            for factor in world.factors
        ],
        "lygus": {  # 修改为lygus
            "health": world.lygus.health,
            "is_awakened": world.lygus.is_awakened
        },
        "iron_tomb": {
            "is_active": world.iron_tomb.is_active,
            "progress": world.iron_tomb.progress,
            "unlocked_factors": [factor.value for factor in world.iron_tomb.unlocked_factors]
        },
        "save_timestamp": datetime.now().isoformat()
    }
    
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(save_data, f, indent=2, ensure_ascii=False)

def load_game_state(filename: str) -> GameWorld:
    """从文件加载游戏状态"""
    with open(filename, 'r', encoding='utf-8') as f:
        save_data = json.load(f)
    
    world = GameWorld()
    world.current_time = save_data["current_time"]
    world.current_cycle = save_data["current_cycle"]
    world.iron_curtain_progress = save_data["iron_curtain_progress"]
    
    # 重新创建因子
    for factor_data in save_data["factors"]:
        factor_type = FactorType(factor_data["type"])
        factor = FactorDevelopment(factor_type, factor_data["name"], "")
        factor.level = factor_data["level"]
        factor.current_location = tuple(factor_data["location"])
        factor.attributes = factor_data["attributes"]
        factor.skills = factor_data["skills"]
        world.factors.append(factor)
    
    # 恢复Lygus状态
    world.lygus.health = save_data["lygus"]["health"]  # 修改为lygus
    world.lygus.is_awakened = save_data["lygus"]["is_awakened"]  # 修改为lygus
    
    # 恢复铁墓状态
    world.iron_tomb.is_active = save_data["iron_tomb"]["is_active"]
    world.iron_tomb.progress = save_data["iron_tomb"]["progress"]
    world.iron_tomb.unlocked_factors = [
        FactorType(factor_type) for factor_type in save_data["iron_tomb"]["unlocked_factors"]
    ]
    
    return world